<?php
namespace Admin\Controller;

use Think\PageAdmin;
use Common\Support\Curl;
use Think\Upload;

/**
 * 账号管理控制器
 */
class AccountController extends BaseController
{

    /**
     * 初始化
     *
     * @return [type] [description]
     */
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 工作人员--项目管理员
     * @return [type] [description]
     */
    public function index()
    {
        $count = M('admins')->count();
        $page = new PageAdmin($count, C('PAGE_NUM'));
        $map['r.role_id'] = 3;
        $pages['show'] = $page->show();  //分页输出
        $pages['total'] = $count;  //总数
        $pages['lists'] = M('admins a')
            ->join("left join wk_admins_roles r on a.id=r.admin_id")
            ->order("a.id desc")
            ->where($map)
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->seotitle = '工作人员列表';
        $this->pages = $pages;
        $this->display();
    }

    /**
     * 项目管理员添加
     */
    public function add()
    {
        $roles = M('admin_roles')->where(['id' => ['neq', 1]])->field('id, name')->order('id asc')->select();
        $this->roles = $roles;
        $this->seotitle = '添加工作人员';
        $this->display();
    }

    //项目管理员修改
    function edit()
    {
        $id = I('get.id', 0, 'intval');

        if (!$data = D('admins')->relation('Roles')->where(array('id' => $id))->find()) {
            $this->error("参数错误");
        }

        //已选择管理组
        $alrRoles = array();
        foreach ($data['Roles'] as $item) {
            $alrRoles[] = $item['id'];
        }

        $roles = M('admin_roles')->field('id, name')->order('id asc')->select();

        $this->seotitle = '管理员编辑';
        $this->roles = $roles;
        $this->data = $data;
        $this->alrRoles = $alrRoles;
        $this->display();
    }

    //项目管理员保存
    function save()
    {
        $action = I('get.action', '');
        if ($action == 'add') {   //添加数据

            $d = I('post.', array(), 'trim');

            // 校验
            if ($d['username'] == '') {
                $this->error('请输入用户名');
            }
            if (M('admins')->where(array('username' => $d['username']))->find()) {
                $this->error('用户名已存在');
            }
            if ($d['password'] == '' || $d['repassword'] == '') {
                $this->error('请输入密码或确认密码');
            }
            if ($d['password'] != $d['repassword']) {
                $this->error('密码和确认密码不一致');
            }
            if (!isset($d['role_ids']) || !is_array($d['role_ids']) || count($d['role_ids']) <= 0) {
                $this->error('请选择管理组');
            }

            // 开始写入
            $dbTrans = M();
            $dbTrans->startTrans();

            $user_data = array(
                'uuid' => uuid(),
                'username' => $d['username'],
                'nickname' => $d['nickname'],
                'password' => hash_make($d['password']),
                'created_at' => time(),
                'updated_at' => time(),
                'status' => 1
            );
            $insertid = M('admins')->add($user_data);
            if (!$insertid) {
                $dbTrans->rollback();
                $this->error('写入失败');
            }

            $admins_roles_data = array();
            foreach ($d['role_ids'] as $item) {
                $admins_roles_data[] = array(
                    'admin_id' => $insertid,
                    'role_id' => $item
                );
            }
            $flag = M('admins_roles')->addAll($admins_roles_data);
            if (!$flag) {
                $dbTrans->rollback();
                $this->error('写入失败');
            }

            $dbTrans->commit();
            $this->success('提交成功', U('index'));

        } elseif ($action == 'edit') {   //修改数据
            $id = I('get.id', 0, 'intval');
            $d = I('post.', array(), 'trim');

            // 校验
            if (!M('admins')->where(array('type_id' => 0, 'id' => $id))->find()) {
                $this->error("参数错误");
            }
            if ($d['password'] != '') {
                if ($d['password'] != $d['repassword']) {
                    $this->error('密码和确认密码不一致');
                }
            }
            if (!isset($d['role_ids']) || !is_array($d['role_ids']) || count($d['role_ids']) <= 0) {
                $this->error('请选择管理组');
            }

            // 开始写入
            $dbTrans = D();
            $dbTrans->startTrans();

            $admin_data = array(
                'nickname' => $d['nickname'],
                'updated_at' => time(),
            );
            if ($d['password'] != '') {
                $admin_data['password'] = hash_make($d['password']);
            }
            $flag = M('admins')->where(array('id' => $id))->save($admin_data);
            if ($flag === false) {
                $dbTrans->rollback();
                $this->error('更新失败');
            }

            // 删除未选择的管理组
            $flag = M('admins_roles')->where(array('admin_id' => $id, 'role_id' => array('notin', $d['role_ids'])))->delete();
            if ($flag === false) {
                $dbTrans->rollback();
                $this->error('更新失败');
            }

            $admins_roles_data = array();
            foreach ($d['role_ids'] as $item) {
                if (!M('admins_roles')->where(array('admin_id' => $id, 'role_id' => $item))->find()) {
                    $admins_roles_data[] = array(
                        'admin_id' => $id,
                        'role_id' => $item
                    );
                }
            }

            if (count($admins_roles_data) > 0) {
                $flag = M('admins_roles')->addAll($admins_roles_data);
                if (!$flag) {
                    $dbTrans->rollback();
                    $this->error('更新失败');
                }
            }

            $dbTrans->commit();
            $this->success('提交成功', U('index'));
        } else {
            $this->error("参数错误");
        }
    }

    /**
     * 城市合伙人
     * @return [type] [description]
     */
    public function partner()
    {
        $count = M('partner')->count();
        $page = new PageAdmin($count, C('PAGE_NUM'));

        $pages['show'] = $page->show();  //分页输出
        $pages['total'] = $count;  //总数
        $pages['lists'] = M('partner a')
            ->where(['status' => 1])
            ->order("a.id desc")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->seotitle = '城市合伙人';
        $this->pages = $pages;
        $this->display();
    }

    /**
     * 城市合伙人添加页面展示
     */
    public function partner_add()
    {
        $this->seotitle = '添加城市合伙人';
        $this->display();
    }

    /**
     * 城市合伙人编辑页面展示
     */
    public function partner_upd()
    {
        $id = I('id');
        $data = M('partner')->where(['id' => $id])->find();
        if (!$data)
            $this->error('id有误');

        $this->seotitle = '编辑城市合伙人';
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 城市合伙人添加，修改
     */
    public function partner_add_save()
    {
        $action = I('get.action', '');
        if ($action == 'add') {
            $data = I('post.');
            $data['password'] = md5($data['password']);
            $data['add_time'] = time();

            $res = M('partner')->add($data);
            if ($res) {
                $this->success('添加成功', U('partner'));
            } else {
                $this->success('添加失败');
            }
        } elseif ($action == 'save') {
            $data = I('post.');
            $data['password'] = md5($data['password']);
            $data['update_time'] = time();
            $res = M('partner')->where(['id' => $data['id']])->save($data);
            if ($res) {
                $this->success('编辑成功', U('partner'));
            } else {
                $this->success('编辑失败');
            }
        }
    }

    /**
     * 客户(审核员)
     * @return [type] [description]
     */
    public function audit()
    {
        $count = M('audit')->count();
        $page = new PageAdmin($count, C('PAGE_NUM'));

        $pages['show'] = $page->show();  //分页输出
        $pages['total'] = $count;  //总数
        $pages['lists'] = M('audit a')
            ->where(['status' => 1])
            ->order("a.id desc")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->seotitle = '审核员信息';
        $this->pages = $pages;
        $this->display();
    }

    /**
     * 添加页面展示
     */
    public function audit_add()
    {
        //物料
        $info = M('materiel')->select();
        $this->seotitle = '添加审核员';
        $this->assign('info', $info);
        $this->display();
    }

    /**
     * 修改页面展示
     */
    public function audit_upd()
    {
        $id = I('id');
        $data = M('audit')->where(['id' => $id])->find();
        if (!$data)
            $this->error('id有误');

        $ids = explode(',',$data['materiel']);
        //物料
        $info = M('materiel')->select();
        $this->seotitle = '编辑审核员';
        $this->assign('data', $data);
        $this->assign('ids', $ids);
        $this->assign('info', $info);
        $this->display();
    }

    /**
     * 添加，修改
     */
    public function audit_add_save()
    {
        $action = I('get.action', '');
        if ($action == 'add') {
            $data = I('post.');
            $data['password'] = md5($data['password']);
            $data['add_time'] = time();
            if (is_array($data['materiel'])) {
                $data['materiel'] = implode($data['materiel'], ',');
            } else {
                $data['materiel'] = '';
            }

            $res = M('audit')->add($data);
            if ($res) {
                $this->success('添加成功', U('audit'));
            } else {
                $this->success('添加失败');
            }
        } elseif ($action == 'save') {
            $data = I('post.');
            $data['password'] = md5($data['password']);
            $data['update_time'] = time();
            if (is_array($data['materiel'])) {
                $data['materiel'] = implode($data['materiel'], ',');
            } else {
                $data['materiel'] = '';
            }
            //var_dump($data['materiel']);die;
            $res = M('audit')->where(['id' => $data['id']])->save($data);
            if ($res) {
                $this->success('编辑成功', U('audit'));
            } else {
                $this->success('编辑失败');
            }
        }
    }

    /**
     * 删除
     */
    public function delete()
    {
        $id = I('id');
        $table = I('tab');

        $info = M($table)->where(['id' => $id])->find();
        if ($info) {
            $rs = M($table)->where(['id' => $id])->save(['status' => 0, 'update_time' => time()]);
            if ($rs) {
                $this->success('删除成功', U($table));
            } else {
                $this->error('删除失败，服务器异常');
            }
        } else {
            $this->error('删除失败，id有误');
        }
    }

    /**
     * 详情
     */
    public function detail()
    {
        $id = I('id');
        $table = I('tab');

        $data = M($table)->where(['id' => $id])->find();
        $this->assign('data', $data);
        if ($table == 'audit') {
            $seotitie = '审核员详情';
        } else {
            $seotitie = '城市合伙人详情';
        }
        $this->seotitle = $seotitie;;
        $this->display($table . '_detail');
    }

    /**
     * 获取不重复的邀请码
     * @return string
     */
    public function getInviteCode()
    {
        //1为数字，其他为英文+数字，默认为数字
        $code = getInviteCode(1);
        $res = M('partner')->where(['invite_code' => $code])->find();
        if ($res) {
            $this->getInviteCode();
        }

        exit(json_encode($code));
    }
}